/*
 * Trilogy instant messaging system
 * Nathan Reitz, Aaron Mertz, Dave Clark
 * 11/14/2007
*/

package edu.psu.ist.ist311.trilogyIM;

import java.awt.Container;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class BuddyWindow extends JFrame implements ActionListener{

	private Sender sender;
	private JMenuBar mainMenuBar;
	private JMenu mainMenu;
	private JMenuItem createAccountMI, sendMessageMI, loginMI, logoutMI;
	private JLabel accountName;
	private CreateAccount createAccount;
	private LoginScreen loginScreen;
    private JButton addRemove;
    private JScrollPane buddyList;
    private JList listContents;
    private JButton sendIm;
    private ArrayList buddies;
	
	XMLEncoder xe;
	XMLDecoder xd;
	String Readname;
	String Readpass;

	
	public BuddyWindow(){
		super("Trilogy IM Client");
		
		//inits some values
		sender = null;
		accountName = new JLabel("Account Name Here", JLabel.CENTER);
		this.add(accountName,BorderLayout.PAGE_START);
		createAccount = new CreateAccount(this);
		loginScreen = new LoginScreen(this);
		this.createGui();
		
		this.notNormal(loginScreen);
	}
	
	public void createGui() {	//used to create the frame and look
	
		//creates the main menu
        mainMenuBar = new JMenuBar();
        mainMenu = new JMenu("Main Menu");
        mainMenuBar.add(mainMenu);
    
        //creates the buddy list with dummy buddies
        buddies = new ArrayList();
        buddies.add("Josh");
        buddies.add("Yang");
        buddies.add("The President");
    
        buddyList = new javax.swing.JScrollPane();
        listContents = new JList(buddies.toArray());
        listContents.setSelectionMode(0);
        addRemove = new javax.swing.JButton();
        sendIm = new javax.swing.JButton();
        
        //Create "Create Account" Menu Item and add it to menu
        createAccountMI = new JMenuItem("Create Account",KeyEvent.VK_C);
        createAccountMI.addActionListener(this);
        mainMenu.add(createAccountMI);
        
        //Create "Login" Menu Item and add it to menu
        loginMI = new JMenuItem("Log In",KeyEvent.VK_L);
        loginMI.addActionListener(this);
        mainMenu.add(loginMI);
        
        //Create "Send Message" Menu Item and add it to menu
        sendMessageMI = new JMenuItem("Send Message",KeyEvent.VK_S);
        sendMessageMI.addActionListener(this);
        mainMenu.add(sendMessageMI);
        sendMessageMI.setEnabled(false);
        
        //Create Logout Menu Item and add it
        logoutMI = new JMenuItem("Logout",KeyEvent.VK_O);
        logoutMI.addActionListener(this);
        mainMenu.add(logoutMI);
        logoutMI.setEnabled(false);
        
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        
        //sets buddy list to scroll pane
        buddyList.setViewportView(listContents);

        addRemove.setText("Add (Not Implemented)");
        sendIm.setText("Send IM");
        
        //send IM listener
        sendIm.addActionListener(this);

        //sets the menu and inits buddy list
        setJMenuBar(mainMenuBar);
        this.normal();
	}
	
	public void normal(){
		
		if(createAccount.isDisplayable())
			this.remove(createAccount);
		if(loginScreen.isDisplayable())
			this.remove(loginScreen);
		
			//generated by netbeans
			javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
	        getContentPane().setLayout(layout);
	        layout.setHorizontalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	                    .addGroup(layout.createSequentialGroup()
	                        .addComponent(addRemove)
	                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
	                        .addComponent(sendIm, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))
	                    .addComponent(buddyList, javax.swing.GroupLayout.DEFAULT_SIZE, 256, Short.MAX_VALUE))
	                .addContainerGap())
	        );
	        layout.setVerticalGroup(
	            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
	            .addGroup(layout.createSequentialGroup()
	                .addContainerGap()
	                .addComponent(buddyList, javax.swing.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
	                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
	                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
	                    .addComponent(addRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
	                    .addComponent(sendIm, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
	                .addContainerGap())
	        );
        
        this.pack();
        this.setResizable(true);
        this.setVisible(true);
	}
	
	//sets window to a screen besides the buddy window screen
	public void notNormal(JPanel obj){
		this.normal();
		this.remove(this.buddyList);
		this.remove(this.addRemove);
		this.remove(this.sendIm);
		this.setLayout(new BorderLayout());
		this.add(obj,"Center");
		validate();	
	    repaint();
	}
	
	//sets everything back to the buddy list if someone is logged in, login screen otherwise
	public void returnToDefault(){
		normal();
		if(sender==null)
		{
			notNormal(loginScreen);
		}
		else
		{
			validate();	
		    repaint();
		}
	}	
	
	public void actionPerformed(ActionEvent evt) {
		Object event = evt.getSource();
		//if the create menu item is pressed
		if((event==createAccountMI)){
			this.notNormal(createAccount);
		}
		//if the send message menu item is pressed, doesnt work yet
		else if((event == sendMessageMI)||(event == sendIm) && listContents.isSelectionEmpty()!=true){
			
			//creates dummy receiver for conversation
			Receiver rec1 = new Receiver(listContents.getSelectedValue().toString());
			
			//Starts the conversation window
			Conversation convo = new Conversation(sender,rec1);
		}
		else if((event==loginMI)){
			this.notNormal(loginScreen);
		}
		else if((event==logoutMI)){
			sender = null;
			this.sendMessageMI.setEnabled(false);
			this.logoutMI.setEnabled(false);
			this.returnToDefault();
		}
		//if the create account pane is open and ok is pressed
		else if((event==createAccount.ok)){
			//makes sure the username and pass are long/short enough
			if(createAccount.getUsername().length() >0 && createAccount.getUsername().length() < 20){
				if(createAccount.getPassword().length() >0 && createAccount.getPassword().length() < 20){
       
					//write to an XML file
					
					try {
			               xe = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(createAccount.getUsername()+".xml")));
			              }
			         catch(Exception xx) {xx.printStackTrace();}
			     //------------------------------------------------------------------------------        
			         try {
			        xe.writeObject(createAccount.getUsername());
			        xe.writeObject(createAccount.getPassword());
			             }
			         catch(Exception xx) {xx.printStackTrace();}
			     //------------------------------------------------------------------------------        
			         try {
			              xe.close();
			             }
			         catch(Exception xx) {xx.printStackTrace();}
			        }
			    }

			remove(createAccount);
			this.returnToDefault();
		}
//		if the create account pane is open and cancel is pressed
		else if (event == createAccount.cancel){
			//remove the create account panel from the Buddy Window
			returnToDefault();
		}
		else if (event == loginScreen.login){
			//this.sender = new Sender("Trilogy");
			if(loginScreen.getUsername().length() >0 && loginScreen.getUsername().length() < 20){
				if(loginScreen.getPassword().length() >0 && loginScreen.getPassword().length() < 20){

				    try {
				         xd = new XMLDecoder(new BufferedInputStream(new FileInputStream(loginScreen.getUsername()+".xml")));
				              
				     //------------------------------------------------------------------------------        
				         try {
						        Readname = (String)xd.readObject();
						        Readpass = (String)xd.readObject();
						        System.out.println(Readname);
						        System.out.println(Readpass);
						        repaint();
				             }
				         catch(Exception xx) {xx.printStackTrace();}
				     //------------------------------------------------------------------------------        
				         try {
				              xd.close();
				             }
				         catch(Exception xx) {xx.printStackTrace();}
				         
				         sender = new Sender(loginScreen.getUsername());
				         this.sendMessageMI.setEnabled(true);
						 this.logoutMI.setEnabled(true);
						 this.normal();
							
				    }
				    
				    catch(Exception xx) {}
				}
			}
		}
		else if (event == loginScreen.cancel){
			//remove the create account panel from the Buddy Window
			returnToDefault();
			}
	}
}

